# baidu_ai.py 文件内容
from aip import AipSpeech

""" 你的 APPID AK SK """
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)


def audio_to_text(pcm_file):
    # 读取文件 , 终于得到了PCM文件
    with open(pcm_file, 'rb') as fp:
        file_context = fp.read()

    # 识别本地文件
    res = client.asr(file_context, 'pcm', 16000, {
        'dev_pid': 1536,
    })

    # 确定识别除正确的结果
    if (res['err_msg'] == 'success.'):
        # 从字典里面获取"result"的value 列表中第1个元素,就是识别出来的字符串"老男孩教育"
        res_str = res.get("result")[0]
    else:
        res_str = ''

    return res_str


def text_to_audio(res_str):
    synth_file = "synth.mp3"
    synth_context = client.synthesis(res_str, "zh", 1, {
        "vol": 5,
        "spd": 4,
        "pit": 9,
        "per": 4
    })

    with open(synth_file, "wb") as f:
        f.write(synth_context)

    return synth_file
